﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Text;

namespace HelpNetwork
{
    class SocketServer
    {
        public static bool keepAlive = true;
        public static void createNewServer()
        {
            TcpListener serverSocket = new TcpListener(IPAddress.Any,8888);
            int requestCount = 0;
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Principal.mainForm.inserareMesaj("S-a pornit server-ul pe port-ul 8888");
            clientSocket = serverSocket.AcceptTcpClient();
            Principal.mainForm.inserareMesaj("Server-ul a acceptat o conexiune de la client.");
            requestCount = 0;
            keepAlive = true;
            while (keepAlive == true)
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[10025];
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    if (String.Compare(dataFromClient, "Stop") == 0)
                        keepAlive = false;
                    Principal.mainForm.inserareMesaj("Clientul: " + dataFromClient);
                    string serverResponse = "Temp: " + Principal.mainForm.appParam.parametriiCurenti.tempAmbientala.ToString() + "Umiditate: " + Principal.mainForm.appParam.parametriiCurenti.umiditate.ToString() + "Lumina: " +Principal.mainForm.appParam.parametriiCurenti.lumina.ToString();
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Principal.mainForm.inserareMesaj("Serverul: " + serverResponse);
                }
                catch (Exception ex)
                {
 //                   Principal.mainForm.inserareMesaj(ex.ToString());
                    keepAlive = false;
                }
            }

            clientSocket.Close();
            serverSocket.Stop();
            Principal.mainForm.inserareMesaj("Server-ul s-a oprit.");

        }
    }
}
